package com.example.mytestdemo.scale.zoom;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;

import androidx.core.view.GestureDetectorCompat;


/**
 * @Description:支持控件缩放，旋转, 双击放大缩小，绘制， 生成图片等
 * @Author: tgw
 * @CreateDate: 2022/4/22 10:46
 */
public class HomeworkZoomView extends FrameLayout {
    String TAG = "HomeworkZoomView";
    // 属性变量
    private float translationX; // 移动X
    private float translationY; // 移动Y
    private float mScaleFactor = 1; // 伸缩比例
    private int mRotation; // 旋转角度

    // 移动过程中临时变量
    private float actionX;
    private float actionY;
    private float spacing;
    private int moveType; // 0=未选择，1=correct_tool_drag，2=缩放

    //动画正在执行中
    private boolean isDoing = false;

    private static final int DEFAULT_SCALE_DURATION = 300;
    private static final String PROPERTY_SCALE = "scale";
    private static final String PROPERTY_TRANX = "tranX";
    private static final String PROPERTY_TRANY = "tranY";
    private static final float MAX_SCALE = 2.0f;
    private static final float MIN_SCALE = 1.0f;

    GestureDetectorCompat mGestureDetector;

    private float mLastTouchX;
    private float mLastTouchY;

    private int originWidth; //控件的原始长度
    private int originHeight; //控件的原始宽度
    private float originScale = 1; //缩放的回弹参数

    private boolean isOpenMultiFingered = false;

    public HomeworkZoomView(Context context) {
        this(context, null);
    }

    public HomeworkZoomView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HomeworkZoomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setClickable(true);
        init(context);
    }

    private void init(Context context) {
        mGestureDetector = new GestureDetectorCompat(getContext(), new CorrectGestureListener());
//        service = ARouter.getInstance().navigation(MultiFingeredPaintService.class);
//        if(service != null){
//            isOpenMultiFingered = service.isOpenMultiFingered();
//        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //获取控件的长宽
        originWidth = MeasureSpec.getSize(widthMeasureSpec);
        originHeight = MeasureSpec.getSize(heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //getParent().requestDisallowInterceptTouchEvent(true);
//        if(ev.getAction() == MotionEvent.ACTION_MOVE){
//            if(mScaleFactor == 1){
//                return false;
//            }
//        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        return super.dispatchTouchEvent(ev);
    }

    public interface OnSetTouchEventListener {
        void setTouchEvent(MotionEvent event);

        void cancel();
    }

    private OnSetTouchEventListener setTouchEventListener;

    public void setTouchEvent(OnSetTouchEventListener setTouchEventListener) {
        this.setTouchEventListener = setTouchEventListener;
    }

    boolean notDo = false;


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Log.e("seesee", "onTouchEvent " + event.getActionMasked());

        if (isDoing) {
            return super.onTouchEvent(event);
        }
        if (isOpenMultiFingered) {
            if (event.getPointerCount() == 1) {
                if (setTouchEventListener != null) {
                    setTouchEventListener.setTouchEvent(event);
                    getParent().requestDisallowInterceptTouchEvent(true);
                    return super.onTouchEvent(event);
                }

            }
            if (event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
                if (setTouchEventListener != null) {
                    setTouchEventListener.cancel();
                }
            }
        }

        //注册双击事件
        if (mGestureDetector != null) {
            boolean a = mGestureDetector.onTouchEvent(event);

        }
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                moveType = 1;
                actionX = event.getRawX();
                actionY = event.getRawY();
                //getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                moveType = 2;
                spacing = getSpacing(event);
                mLastTouchX = event.getRawX();
                mLastTouchY = event.getRawY();
                Log.d(TAG, "onTouchEvent ACTION_POINTER_DOWN mLastTouchX: " + mLastTouchX);
                Log.d(TAG, "onTouchEvent ACTION_POINTER_DOWN mLastTouchY: " + mLastTouchY);
                // getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_MOVE:
                if (isOpenMultiFingered) {
                    Log.d(TAG, "onTouchEvent isOpenMultiFingered mScaleFactor: " + mScaleFactor);
                    Log.d(TAG, "onTouchEvent isOpenMultiFingered spacing: " + spacing);
                    mScaleFactor = mScaleFactor * getSpacing(event) / spacing;
                    Log.d(TAG, "onTouchEvent isOpenMultiFingered mScaleFactor: " + mScaleFactor);


                    boolean canScale = checkScaleBound();
                    if (canScale) {
                        //缩放过程中位置偏移
                        float disX = event.getRawX() - mLastTouchX;
                        float disY = event.getRawY() - mLastTouchY;
                        Log.d(TAG, "onTouchEvent isOpenMultiFingered translationX: " + translationX);
                        Log.d(TAG, "onTouchEvent isOpenMultiFingered translationY: " + translationY);
                        setTranslationXY(translationX + disX, translationY + disY);

                    }

                    mLastTouchX = event.getRawX();
                    mLastTouchY = event.getRawY();
                } else {
                    if (moveType == 1) {
                        boolean canMove = false;
                        if (mRotation == 90 || mRotation == 270) {
                            canMove = checkRotationTranslation(event.getRawX() - actionX, event.getRawY() - actionY);
                        } else {
                            canMove = checkTranslation(event.getRawX() - actionX, event.getRawY() - actionY);
                        }
                        actionX = event.getRawX();
                        actionY = event.getRawY();
                        if (!canMove) {

                            zoomNotHandler = true;

                            getParent().requestDisallowInterceptTouchEvent(false);


                        } else {
                            zoomNotHandler = false;
                        }

                    } else if (moveType == 2) {
                        Log.d(TAG, "onTouchEvent moveType == 2 mScaleFactor: " + mScaleFactor);
                        Log.d(TAG, "onTouchEvent moveType == 2 spacing: " + spacing);
                        mScaleFactor = mScaleFactor * getSpacing(event) / spacing;
                        Log.d(TAG, "onTouchEvent moveType == 2 mScaleFactor: " + mScaleFactor);
                        boolean canScale = checkScaleBound();
                        if (canScale) {
                            //缩放过程中位置偏移
                            float disX = event.getRawX() - mLastTouchX;
                            float disY = event.getRawY() - mLastTouchY;
                            Log.d(TAG, "onTouchEvent moveType == 2 mLastTouchX: " + mLastTouchX);
                            Log.d(TAG, "onTouchEvent moveType == 2 mLastTouchY: " + mLastTouchY);
                            Log.d(TAG, "onTouchEvent moveType == 2 disX: " + disX);
                            Log.d(TAG, "onTouchEvent moveType == 2 disY: " + disY);
                            Log.d(TAG, "onTouchEvent moveType == 2 event.getRawX(): " + event.getRawX());
                            Log.d(TAG, "onTouchEvent moveType == 2  event.getRawY(): " + event.getRawY());
                            Log.d(TAG, "onTouchEvent moveType == 2  translationX: " + translationX);
                            Log.d(TAG, "onTouchEvent moveType == 2  translationY: " + translationY);
                            setTranslationXY(translationX + disX, translationY + disY);

                        }

                        mLastTouchX = event.getRawX();
                        mLastTouchY = event.getRawY();
                        Log.d(TAG, "onTouchEvent moveType == 2  endm LastTouchX: " + mLastTouchX);
                        Log.d(TAG, "onTouchEvent moveType == 2  endm mLastTouchY: " + mLastTouchY);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                upAnimator(moveType);
                moveType = 0;

        }


        return super.onTouchEvent(event);
    }

    private boolean checkTranslation(float disX, float disY) {
        //判断左右滑，还是上下滑

        //如果绘制区域在可视范围内，则不能滑动x，y坐标
        int width = originWidth;
        int height = originHeight;
        float tempWidth = width * mScaleFactor;
        float tempHeight = height * mScaleFactor;
//        if(mRotation == 90 || mRotation == 270){
//            tempWidth = height*mScaleFactor;
//            tempHeight = width*mScaleFactor;
//        }
        Log.d(TAG, "checkTranslation width: " + width);
        Log.d(TAG, "checkTranslation height: " + height);
        Log.d(TAG, "checkTranslation mScaleFactor: " + mScaleFactor);
        Log.d(TAG, "checkTranslation tempWidth: " + tempWidth);
        Log.d(TAG, "checkTranslation tempHeight: " + tempHeight);

        boolean canMove = true;

        if (tempWidth <= width && tempHeight <= height) {
            return false;
        }
        float resultX = translationX + disX;
        float resultY = translationY + disY;
        Log.d(TAG, "checkTranslation disX: " + disX);
        Log.d(TAG, "checkTranslation disY: " + disY);
        Log.d(TAG, "checkTranslation translationX: " + translationX);
        Log.d(TAG, "checkTranslation translationY: " + translationY);
        Log.d(TAG, "checkTranslation resultX: " + resultX);
        Log.d(TAG, "checkTranslation resultY: " + resultY);

        if (tempWidth <= width) {
            resultX = translationX; //不动
        } else {
            float maxWDis = (tempWidth - width) / 2;
            if (resultX <= -maxWDis) {
                resultX = -maxWDis;
                canMove = false;
            } else if (resultX >= maxWDis) {
                resultX = maxWDis;
                canMove = false;
            } else {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
        }

        if (tempHeight <= height) {
            resultY = translationY;
        } else {
            float maxHDis = (tempHeight - height) / 2;
            if (resultY <= -maxHDis) {
                resultY = -maxHDis;
                canMove = false;
            } else if (resultY >= maxHDis) {
                resultY = maxHDis;
                canMove = false;
            } else {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
        }
        if (canMove) {
            //doUp = false;
            setTranslationXY(resultX, resultY);
        }

        return canMove;
    }

    private boolean checkRotationTranslation(float disX, float disY) {
        //判断左右滑，还是上下滑

        //如果绘制区域在可视范围内，则不能滑动x，y坐标
        int width = originWidth;
        int height = originHeight;
        float tempWidth = height * mScaleFactor;
        float tempHeight = width * mScaleFactor;
//        if(mRotation == 90 || mRotation == 270){
//            tempWidth = height*mScaleFactor;
//            tempHeight = width*mScaleFactor;
//        }
        Log.d(TAG, "checkTranslation width: " + width);
        Log.d(TAG, "checkTranslation height: " + height);
        Log.d(TAG, "checkTranslation mScaleFactor: " + mScaleFactor);
        Log.d(TAG, "checkTranslation tempWidth: " + tempWidth);
        Log.d(TAG, "checkTranslation tempHeight: " + tempHeight);

        boolean canMove = true;

        if (tempWidth <= width && tempHeight <= height) {
            return false;
        }
        float resultX = translationX + disX;
        float resultY = translationY + disY;
        Log.d(TAG, "checkTranslation disX: " + disX);
        Log.d(TAG, "checkTranslation disY: " + disY);
        Log.d(TAG, "checkTranslation translationX: " + translationX);
        Log.d(TAG, "checkTranslation translationY: " + translationY);
        Log.d(TAG, "checkTranslation resultX: " + resultX);
        Log.d(TAG, "checkTranslation resultY: " + resultY);

        if (tempWidth <= width) {
            resultX = translationX; //不动
        } else {
            float maxWDis = (tempWidth - width) / 2;
            if (resultX <= -maxWDis) {
                resultX = -maxWDis;
                canMove = false;
            } else if (resultX >= maxWDis) {
                resultX = maxWDis;
                canMove = false;
            } else {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
        }

        if (tempHeight <= height) {
            resultY = translationY;
        } else {
            float maxHDis = (tempHeight - height) / 2;
            if (resultY <= -maxHDis) {
                resultY = -maxHDis;
                canMove = false;
            } else if (resultY >= maxHDis) {
                resultY = maxHDis;
                canMove = false;
            } else {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
        }
        if (canMove) {
            //doUp = false;
            setTranslationXY(resultX, resultY);
        }

        return canMove;
    }

    private void upAnimator(int moveType) {
        if (isDoing || moveType != 2) return; //双击事件缩放中返回
        int width = originWidth;
        int height = originHeight;
        float tempWidth = width * mScaleFactor;
        float tempHeight = height * mScaleFactor;
        if (mRotation == 90 || mRotation == 270) {
            tempWidth = height * mScaleFactor;
            tempHeight = width * mScaleFactor;
        }

        //没有变化则不需要判断
        if (translationX == 0 && translationY == 0 && mScaleFactor == originScale) {
            return;
        }

        float resultX;
        float resultY;
        if (mRotation == 90 || mRotation == 270) {
            resultX = ((1 - mScaleFactor) * originHeight) + Math.abs(translationX);
            resultY = ((1 - mScaleFactor) * originWidth) + Math.abs(translationY);

            Log.d(TAG, "upAnimator mScaleFactor: " + mScaleFactor);
            Log.d(TAG, "upAnimator tempHeight: " + tempHeight);
            Log.d(TAG, "upAnimator tempWidth: " + tempWidth);
            Log.d(TAG, "upAnimator width: " + width);
            Log.d(TAG, "upAnimator height: " + height);
            Log.d(TAG, "upAnimator (1 - mScaleFactor) * originHeight: " + (1 - mScaleFactor) * originHeight);
            Log.d(TAG, "upAnimator (1 - mScaleFactor) * originWidth: " + (1 - mScaleFactor) * originWidth);
            Log.d(TAG, "upAnimator ((1 - mScaleFactor) * originHeight - width) / 2: " + ((1 - mScaleFactor) * originHeight - width) / 2);
            Log.d(TAG, "upAnimator ((1 - mScaleFactor) * originWidth - height) / 2: " + ((1 - mScaleFactor) * originWidth - height) / 2);
            Log.d(TAG, "upAnimator translationX: " + translationX);
            Log.d(TAG, "upAnimator translationY: " + translationY);
            Log.d(TAG, "upAnimator resultX: " + resultX);
            Log.d(TAG, "upAnimator resultY: " + resultY);
            boolean isNeedBack = isRotationNeedBack(mScaleFactor, resultX, resultY,originWidth ,originHeight );
            //根据观察，向下滑translationY大于0，向上滑translationY小于0
            //在缩放系数小于1的时候，resultY永远大于0，当缩小时，缩小的距离加上 移动距离的绝对值小于当前的布局的一半时
//            if(mScaleFactor <1 && resultY > (float) originWidth/2){
//                isNeedBack = true;
//            }else if(mScaleFactor >1&&resultY>0){  //在缩放系数>于1的时候，resultY永远大于0，当缩小时，缩小的距离加上 移动距离的绝对值小于当前的布局的一半时
//                isNeedBack = true;
//            }
//
//            if(mScaleFactor <1 && resultX > (float) originHeight/2){
//                isNeedBack = true;
//            }else if(mScaleFactor >1&&resultX>0){
//                isNeedBack = true;
//            }

            if (isNeedBack) {
                zoomAnimator(mScaleFactor, originScale, 0, 0);
                return;
            }
            if (mScaleFactor <= MIN_SCALE) {
                mScaleFactor = MIN_SCALE;
                zoomAnimator(mScaleFactor, originScale, 0, 0);
            } else if (mScaleFactor >= MAX_SCALE) {
                mScaleFactor = MAX_SCALE;
                zoomAnimator(mScaleFactor, originScale, 0, 0);
            }

        } else {
//            resultX = (1 - mScaleFactor) * originWidth / 2 + translationX;
//            resultY = (1 - mScaleFactor) * originHeight / 2 + translationY;
//            boolean isNeedBack = isNeedBack(resultX, resultY, tempWidth, tempHeight);
//
//            if (isNeedBack) {
//                zoomAnimator(mScaleFactor, originScale, 0, 0);
//            }
            resultX = ((1 - mScaleFactor) *originWidth ) + Math.abs(translationX);
            resultY = ((1 - mScaleFactor) * originHeight) + Math.abs(translationY);
            boolean isNeedBack = isRotationNeedBack(mScaleFactor, resultX, resultY,originHeight  , originWidth);
            if (isNeedBack) {
                zoomAnimator(mScaleFactor, originScale, 0, 0);
                return;
            }
            if (mScaleFactor < MIN_SCALE) {
                mScaleFactor = MIN_SCALE;
                zoomAnimator(mScaleFactor, originScale, 0, 0);
            } else if (mScaleFactor > MAX_SCALE) {
                mScaleFactor = MAX_SCALE;
                zoomAnimator(mScaleFactor, originScale, 0, 0);
            }
        }


    }

    private boolean isNeedBack(float resultX, float resultY, float tempWidth, float tempHeight) {
        if (resultX > 0) {
            return true;
        } else if ((resultX + tempWidth) < originWidth) {
            return true;
        }

        if (resultY > 0) {
            return true;
        } else if ((resultY + tempHeight) < originHeight) {
            return true;
        }
        return false;
    }

    private boolean isRotationNeedBack(float scaleFactor, float resultX, float resultY,float originHeight, float originWidth ) {
        //根据观察，向下滑translationY大于0，向上滑translationY小于0
        //在缩放系数小于1的时候，resultY永远大于0，当缩小时，缩小的距离加上 移动距离的绝对值，小于当前的布局的一半时，
        // 认为你应该要恢复原状了，防止缩小时 偏移到到看不见了

        //在缩放系数大于1的时候，((1 - mScaleFactor) * originWidth)的值，假设mScaleFactor为最大的2倍时，
        // 当未移动时resultY=-originWidth，当移动后就会translationX就会产生偏移量（上面取得绝对值：即偏移量）
        //当缩小时，((1 - mScaleFactor) * originWidth)的值会变小，当缩放的大小+偏移量>0时
        // 认为整体应该要恢复原状了，防止缩小时 偏移到到看不见了
        boolean isNeedBack = false;
        if (scaleFactor < 1 && resultY > (float) originHeight / 2) {//当90°时原始宽高颠倒
            isNeedBack = true;
        } else if (scaleFactor > 1 && resultY > 0) {
            //在缩放系数>于1的时候，resultY永远大于0，当缩小时，
            // 缩小的距离加上 移动距离的绝对值小于当前的布局的一半时
            isNeedBack = true;
        }

        if (scaleFactor < 1 && resultX > (float) originWidth / 2) {
            isNeedBack = true;
        } else if (scaleFactor > 1 && resultX > 0) {
            isNeedBack = true;
        }
        return isNeedBack;
    }


    private void setTranslationXY(float transX, float transY) {
        translationX = transX;
        translationY = transY;
        Log.d(TAG, "setTranslationXY translationX: " + translationX);
        Log.d(TAG, "setTranslationXY translationY: " + translationY);
        //Log.e("xxyy", "translationX="+translationX+" || translationY="+translationY);
        setTranslationX(translationX);
        setTranslationY(translationY);
    }

    /**
     * 缩放边界值判断
     *
     * @return 判断达到边界值停止后续操作
     */
    private boolean checkScaleBound() {
        boolean canScale;
        Log.d(TAG, "checkScaleBound--mScaleFactor: " + mScaleFactor);
        if (mScaleFactor < MIN_SCALE) {
            canScale = false;
            mScaleFactor = MIN_SCALE;
        } else if (mScaleFactor > MAX_SCALE) {
            canScale = false;
            mScaleFactor = MAX_SCALE;
        } else {
            canScale = true;
            getParent().requestDisallowInterceptTouchEvent(true);
        }
        setScaleX(mScaleFactor);
        setScaleY(mScaleFactor);
        return canScale;
    }

    public final void doSetRotation(int rotation) {
        this.mRotation = rotation;
        float tempScale = 1;
        setTranslationX(translationX = 0);
        setTranslationY(translationY = 0);
        if (mRotation == 0) {
            originScale = 1;
            tempScale = 1;
        } else if (mRotation == 90) {
            originScale = (float) this.getHeight() / this.getWidth();
            tempScale = originScale;
        } else if (mRotation == 180) {
            originScale = 1;
            tempScale = 1;
        } else if (mRotation == 270) {
            originScale = (float) this.getHeight() / this.getWidth();
            tempScale = originScale;
        }

        mScaleFactor = mScaleFactor * tempScale;
        checkScaleBound();
        this.setRotation(mRotation);
    }

    /**
     * 对外方法，动态旋转，规定四个角度,顺时针
     */
    public final void doSetCWRotation(){
        float tempScale = 1;

        setTranslationX(translationX = 0);
        setTranslationY(translationY = 0);
        if(mRotation == 0){
            originScale = (float) this.getHeight()/this.getWidth();
            tempScale = originScale;
            mRotation = 90;
        }else if(mRotation == 90){
            originScale = 1;
            tempScale = (float) this.getWidth()/this.getHeight();
            mRotation = 180;
        }else if(mRotation == 180){
            originScale = (float) this.getHeight()/this.getWidth();
            tempScale = originScale;
            mRotation = 270;
        }else if(mRotation == 270){
            originScale = 1;
            tempScale = (float) this.getWidth()/this.getHeight();
            mRotation = 0;
        }

//        Log.d(TAG, "doSetRotation mRotation: "+mRotation);
//        Log.d(TAG, "doSetRotation originScale: "+originScale);
//        Log.d(TAG, "doSetRotation tempScale: "+tempScale);
//        Log.d(TAG, "doSetRotation translationX: "+translationX);
//        Log.d(TAG, "doSetRotation translationY: "+translationY);
//        Log.d(TAG, "doSetRotation getWidth(): "+getWidth());
//        Log.d(TAG, "doSetRotation getHeight(): "+getHeight());

        mScaleFactor = mScaleFactor * tempScale;
        checkScaleBound();
        this.setRotation(mRotation);
        if(setRotationListener != null){
            setRotationListener.setRotation(position, mRotation);
        }
    }

    /**
     * 对外方法，动态旋转，规定四个角度，逆时针
     */
    public final void doSetCCWRotation(){
        float tempScale = 1;

        setTranslationX(translationX = 0);
        setTranslationY(translationY = 0);
        if(mRotation == 0){
            originScale = (float) this.getHeight()/this.getWidth();
            tempScale = originScale;
            mRotation = 270;
        }else if(mRotation == 90){
            originScale = 1;
            tempScale = (float) this.getWidth()/this.getHeight();
            mRotation = 0;
        }else if(mRotation == 180){
            originScale = (float) this.getHeight()/this.getWidth();
            tempScale = originScale;
            mRotation = 90;
        }else if(mRotation == 270){
            originScale = 1;
            tempScale = (float) this.getWidth()/this.getHeight();
            mRotation = 180;
        }

//        Log.d(TAG, "doSetRotation mRotation: "+mRotation);
//        Log.d(TAG, "doSetRotation originScale: "+originScale);
//        Log.d(TAG, "doSetRotation tempScale: "+tempScale);
//        Log.d(TAG, "doSetRotation translationX: "+translationX);
//        Log.d(TAG, "doSetRotation translationY: "+translationY);
//        Log.d(TAG, "doSetRotation getWidth(): "+getWidth());
//        Log.d(TAG, "doSetRotation getHeight(): "+getHeight());

        mScaleFactor = mScaleFactor * tempScale;
        checkScaleBound();
        this.setRotation(mRotation);
        if(setRotationListener != null){
            setRotationListener.setRotation(position, mRotation);
        }
    }

    // 触碰两点间距离
    private float getSpacing(MotionEvent event) {
        //通过三角函数得到两点间的距离
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    public Bitmap getBitmap() {


        int width = this.getWidth();
        int height = this.getHeight();
        if (height <= 0 || width <= 0) {
            return null;
        }
        Bitmap mScreenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);


        Canvas c = new Canvas(mScreenshot);
        c.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        this.draw(c);

        return mScreenshot;
    }

    public int getmRotation() {
        return this.mRotation;
    }

    public void setAddScale(float add) {
        mScaleFactor = mScaleFactor+add;
        checkScaleBound();
        upAnimator(2);
    }

    public void setReduceScale(float reduce) {
        mScaleFactor = mScaleFactor-reduce;
        checkScaleBound();
        upAnimator(2);
    }

    public Bitmap adjustPhotoRotation() {
        Bitmap bm = getBitmap();
        if (bm == null) return null;
        Matrix m = new Matrix();
        m.setRotate(mRotation, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);

        try {
            Bitmap bm1 = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);

            return bm1;

        } catch (OutOfMemoryError ex) {
        }
        return null;

    }

    /**
     * 双击手势操作
     */
    private class CorrectGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (isDoing) return super.onDoubleTap(e);
            isDoing = true;

            float endFactor;
            float scaleCenterX;
            float scaleCenterY;

            if (mScaleFactor == originScale) {
                scaleCenterX = 0;
                scaleCenterY = 0;
                endFactor = MAX_SCALE;
            } else {
                scaleCenterX = 0;
                scaleCenterY = 0;
                endFactor = originScale;
            }

            zoomAnimator(mScaleFactor, endFactor, scaleCenterX, scaleCenterY);
            return super.onDoubleTap(e);
        }
    }

    private void zoomAnimator(float startVal, float endVal, float scaleCenterX, float scaleCenterY) {
        if (mScaleAnimator == null) {
            newZoomAnimation();
        }
        if (mScaleAnimator.isRunning()) {
            return;
        }

        float startTranX = translationX;
        float startTranY = translationY;
        float endTranX = scaleCenterX;
        float endTranY = scaleCenterY;

        PropertyValuesHolder scaleHolder = PropertyValuesHolder
                .ofFloat(PROPERTY_SCALE, startVal, endVal);
        PropertyValuesHolder tranXHolder = PropertyValuesHolder
                .ofFloat(PROPERTY_TRANX, startTranX, endTranX);
        PropertyValuesHolder tranYHolder = PropertyValuesHolder
                .ofFloat(PROPERTY_TRANY, startTranY, endTranY);
        mScaleAnimator.setValues(scaleHolder, tranXHolder, tranYHolder);
        mScaleAnimator.setDuration(DEFAULT_SCALE_DURATION);
        mScaleAnimator.start();
    }

    ValueAnimator mScaleAnimator;

    /**
     * 缩放动画
     */
    private void newZoomAnimation() {
        mScaleAnimator = new ValueAnimator();
        mScaleAnimator.setInterpolator(new DecelerateInterpolator());
        mScaleAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                //update scaleFactor & tranX & tranY
                float scaleValue = (float) animation.getAnimatedValue(PROPERTY_SCALE);
                float tranXValue = (float) animation.getAnimatedValue(PROPERTY_TRANX);
                float tranYValue = (float) animation.getAnimatedValue(PROPERTY_TRANY);
                mScaleFactor = scaleValue;
                setScaleX(scaleValue);
                setScaleY(scaleValue);
                setTranslationXY(tranXValue, tranYValue);
            }
        });


        mScaleAnimator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {

                isDoing = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mScaleAnimator != null && mScaleAnimator.isRunning()) {
            mScaleAnimator.cancel();
        }
    }

    public interface SetRotationListener {
        void setRotation(int position, int rotation);
    }

    private SetRotationListener setRotationListener;

    public void setSetRotationListener(SetRotationListener listener) {
        this.setRotationListener = listener;
    }

    private int position;

    public void setPosition(int position) {
        this.position = position;
    }

    private String tempName;//生成需要上传的本地路径,上传成功删除

    public void setTempName(String tempName) {
        this.tempName = tempName;
    }

    /**
     * 自己是否不处理
     * true 不处理
     * false 自己处理
     */
    private Boolean zoomNotHandler = null;

    public Boolean getZoomNotHandler() {
        return zoomNotHandler;
    }

}
